# 设置 PROTO 生成路径
set(GENERATE_MAPREDUCE_DIR ${PROJECT_SOURCE_DIR}/lab1/generated)
if (EXISTS "${GENERATE_MAPREDUCE_DIR}" AND IS_DIRECTORY "${GENERATE_MAPREDUCE_DIR}")
    set(MAPREDUCE_PROTO_META_BASE_DIR ${GENERATE_MAPREDUCE_DIR})
else ()
    file(MAKE_DIRECTORY ${GENERATE_MAPREDUCE_DIR})
    set(MAPREDUCE_PROTO_META_BASE_DIR ${GENERATE_MAPREDUCE_DIR})
endif ()

# 设置 proto 搜索路径
set(MAPREDUCE_PROTO_FLAGS ${PROJECT_SOURCE_DIR}/lab1/protos)
# 获取 proto 文件
file(GLOB_RECURSE MAPREDUCE_PROTO_SOURCE_FILES ${MAPREDUCE_PROTO_FLAGS}/*.proto)

foreach (proto_file ${MAPREDUCE_PROTO_SOURCE_FILES})
    get_filename_component(FILE_NAME_WE ${proto_file} NAME_WE)
    get_filename_component(FILE_DIR ${proto_file} DIRECTORY)

    set(CUR_PROTO_SRCS "${MAPREDUCE_PROTO_META_BASE_DIR}/${FILE_NAME_WE}.pb.cc")
    set(CUR_PROTO_HDRS "${MAPREDUCE_PROTO_META_BASE_DIR}/${FILE_NAME_WE}.pb.h")
    set(CUR_PROTO_RPC_SRCS "${MAPREDUCE_PROTO_META_BASE_DIR}/${FILE_NAME_WE}.grpc.pb.cc")
    set(CUR_PROTO_RPC_HDRS "${MAPREDUCE_PROTO_META_BASE_DIR}/${FILE_NAME_WE}.grpc.pb.h")

    list(APPEND MAPREDUCE_PROTO_SRC_CXX_ALL ${CUR_PROTO_SRCS} ${CUR_PROTO_HDRS}
            ${CUR_PROTO_RPC_SRCS} ${CUR_PROTO_RPC_HDRS})

endforeach ()

# 自定义命令
add_custom_command(
        OUTPUT
        ${MAPREDUCE_PROTO_SRC_CXX_ALL}
        COMMAND
        ${_PROTOBUF_PROTOC}
        ARGS
        -I ${MAPREDUCE_PROTO_FLAGS}
        --cpp_out ${MAPREDUCE_PROTO_META_BASE_DIR}
        --grpc_out ${MAPREDUCE_PROTO_META_BASE_DIR}
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        ${MAPREDUCE_PROTO_SOURCE_FILES}
        DEPENDS ${MAPREDUCE_PROTO_SOURCE_FILES}
        COMMENT "Running C++ protocol buffer compiler"
)

add_custom_target(
        generate_mapreduce_proto
        DEPENDS ${MAPREDUCE_PROTO_SRC_CXX_ALL}
)

# 设置生成源文件包含目录变量供上层引用
set(MAPREDUCE_PROTO_GEN_INCLUDE_DIRS ${MAPREDUCE_PROTO_META_BASE_DIR} PARENT_SCOPE)

add_library(lab1_proto ${MAPREDUCE_PROTO_SRC_CXX_ALL})
target_link_libraries(lab1_proto
        ${_REFLECTION}
        ${_GRPC_GRPCPP}
        ${_PROTOBUF_LIBPROTOBUF})
add_dependencies(lab1_proto generate_mapreduce_proto)